﻿using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using OpenWaves.Web;

[assembly: PublicAssemblyResources("OpenWaves.EPiServer.AdminTools.LogViewer.UI.LogFileDownload.ashx")]

namespace OpenWaves.EPiServer.AdminTools.LogViewer.UI
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    public class LogFileDownload : IHttpHandler
    {


        public void ProcessRequest(HttpContext context)
        {
            LogFilePresenter presenter = new LogFilePresenter();


            presenter.Path = context.Request.QueryString[LogFileListing.PathQueryStringParameter];
            presenter.LoadFile();

            if (string.IsNullOrEmpty(presenter.ErrorMessage) == false || presenter.Exception != null || presenter.File == null)
            {
                StringBuilder messageBuilder = new StringBuilder();

                messageBuilder.AppendFormat("Could not load file '{0}'.", presenter.Path);
                messageBuilder.AppendLine();

                messageBuilder.AppendLine(presenter.ErrorMessage);
                messageBuilder.AppendLine();

                if (presenter.Exception != null)
                {
                    messageBuilder.AppendLine(presenter.Exception.ToString());
                }

                PrintErrorMessage(context, messageBuilder.ToString());
                return;
            }



            try
            {
                using (var fileStream = File.Open(presenter.File.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    context.Response.AppendHeader("content-disposition", string.Format(CultureInfo.InvariantCulture, "attachment; filename=\"{0}\"", presenter.File.Name));
                    context.Response.BufferOutput = false;
                    context.Response.OutputStream.Append(fileStream);
                }
            }
            catch (IOException ex)
            {
                StringBuilder messageBuilder = new StringBuilder();
                messageBuilder.AppendFormat(CultureInfo.InvariantCulture, "Failed loading file '{0}'.", presenter.File.Path);
                messageBuilder.AppendLine();
                messageBuilder.AppendLine();

                messageBuilder.AppendLine(ex.Message);

                PrintErrorMessage(context, messageBuilder.ToString());
                Log.Error(ex, "Cannot write file for downloading: {0}.", presenter.File.Path);
            }
        }

        private static void PrintErrorMessage(HttpContext context, string message)
        {
            context.Response.ClearHeaders();
            context.Response.Clear();

            context.Response.ContentType = "text/plain";

            context.Response.Write(message);
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}